package com.softaria.windows.seo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.softaria.windows.model.ModelUrl;
import com.softaria.windows.model.PerspectiveUrl;
import com.softaria.windows.model.ViewUrl;

public class DefaultPerspectiveUrlBuilder implements ModelUrlBuilder, HttpParametersConstants {

  @Override
  public ModelUrl buildModelUrl(ParameterSet parameters) {
    String perspective = parameters.getParameter(HTTP_PARAMETER_PERSPECTIVE);
    String view = parameters.getParameter(HTTP_PARAMETER_VIEW);

    ModelUrl url = null;

    if (perspective != null) {

      if (view == null) {
        url = new PerspectiveUrl(perspective);
      } else {
        String view_parameters = parameters.getParameter(HTTP_PARAMETER_VIEWPARAM);
        url = new ViewUrl(perspective, view, parameters == null ? "" : view_parameters);
      }
    }

    return url;
  }

  @Override
  public ParameterSet extractUrlParameters(ModelUrl perspective) {

    final Map<String, String> params = new HashMap<String, String>();

    params.put(HTTP_PARAMETER_PERSPECTIVE, perspective.getPerspectiveId());

    if (perspective.isView()) {
      ViewUrl viewUrl = (ViewUrl) perspective;
      params.put(HTTP_PARAMETER_VIEW, viewUrl.getViewId());
      if (viewUrl.getParameters() != null) {
        params.put(HTTP_PARAMETER_VIEWPARAM, viewUrl.getParameters());
      }
    }

    return new ParameterSet() {

      @Override
      public String getParameter(String name) {
        return params.get(name);
      }

      @Override
      public Set<String> getParameterNames() {
        return params.keySet();
      }

    };
  }
}
